﻿using MediatR;
using Medical.Api.Read.Application.Command.Wms.WmsOutCauseCommand;
using Medical.Api.Read.Dto.WmsDto.WmsOutDto;
using Medical.Domain.Enum;
using Medical.Domain.Wms;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static Medical.Domain.Enum.DepartmentEnum;

namespace Medical.Api.Read.Application.Handler.Wms.WmsOutCauseHandler
{
    /// <summary>
    /// 出库分页查询处理器，实现分页、时间、状态条件查询。
    /// </summary>
    public class GetOutCauseByPageHandler : IRequestHandler<GetOutCauseByPageCommand, ApiResult<ApiPageIng<WmsOutPageDto>>>
    {
        /// <summary>
        /// 出库主表仓储
        /// </summary>
        private readonly IBaseRepository<WmsOut> _outRepository;
        /// <summary>
        /// 构造函数，注入出库主表仓储
        /// </summary>
        public GetOutCauseByPageHandler(IBaseRepository<WmsOut> outRepository)
        {
            _outRepository = outRepository;
        }
        /// <summary>
        /// 分页查询出库单，支持按创建时间、状态筛选，返回分页结果及状态名
        /// </summary>
        /// <param name="request">分页及筛选参数</param>
        /// <param name="cancellationToken"></param>
        /// <returns>分页出库列表</returns>
        public async Task<ApiResult<ApiPageIng<WmsOutPageDto>>> Handle(GetOutCauseByPageCommand request, CancellationToken cancellationToken)
        {
            // 构建基础查询
            var query = _outRepository.GetAll().Where(x => !x.IsDeleted);
            if (request.QueryDto.StartTime.HasValue)
                query = query.Where(x => x.CreateTime >= request.QueryDto.StartTime.Value);
            if (request.QueryDto.EndTime.HasValue)
                query = query.Where(x => x.CreateTime <= request.QueryDto.EndTime.Value);
            if (request.QueryDto.AuditState.HasValue)
                query = query.Where(x => (int)x.AuditState == request.QueryDto.AuditState.Value);
            
            var total = query.Count();
            // 分页并投影为DTO，状态名直接用ToString（如需中文可用枚举描述）
            var pageData = query.OrderByDescending(x => x.CreateTime)
                .Skip((request.QueryDto.PageIndex - 1) * request.QueryDto.PageSize)
                .Take(request.QueryDto.PageSize)
                .Select(x => new WmsOutPageDto
                {
                    Id = x.Id,
                    OutCode = x.OutCode,
                    OutWarehouse = (WarehouseEnum)(int)x.OutWarehouse,
                    OutWarehouseName = x.OutReason.ToString(),
                    OutReason = (OutCauseEnum)(int)x.OutReason,
                    OutReasonName = x.OutReason.ToString(),
                    AuditState = (ApprovalStateEnum)(int)x.AuditState,
                    AuditStateName = x.AuditState.ToString(),
                    ApplyingUnit = (ApplyingUnitEnum)(int)x.ApplyingUnit,
                    ApplyingUnitName = x.ApplyingUnit.ToString(),
                    AuditName = x.AuditName,
                    AuditDate = x.AuditDate,
                    CreateTime = x.CreateTime
                }).ToList();
            var result = new ApiPageIng<WmsOutPageDto>
            {
                PageData = pageData,
                TotalCount = total
            };
            return await Task.FromResult(new ApiResult<ApiPageIng<WmsOutPageDto>>
            {
                Code = ApiEnums.Success,
                Data = result
            });
        }
    }
}
